package com.xcity.game.activity.exchange;

import java.text.MessageFormat;
import java.util.List;

import com.xcity.Server;
import com.xcity.db.entity.Player;
import com.xcity.game.activity.ActivityService;
import com.xcity.game.activity2.ActivityIds;
import com.xcity.game.common.Cause;
import com.xcity.game.common.MessageConst;
import com.xcity.game.common.PlayerPool;
import com.xcity.game.event.GameEvents;
import com.xcity.game.item.ItemInfo;
import com.xcity.game.item.ItemTemplate;
import com.xcity.pomelo.PomeloRoute;
import com.xcity.pomelo.push.msg.ActivityStatePush;
import com.xcity.pomelo.push.msg.BatchItemsPush;
import com.xcity.pomelo.request.ActivityItemExchangeInfoRequest;
import com.xcity.pomelo.request.ActivityItemExchangeRequest;
import com.xcity.pomelo.response.ActivityItemExchangeInfoResponse;
import com.xcity.pomelo.response.HintResponse;
import com.xcity.pomelo.response.Response;

import naga.x.App;
import naga.x.event.Event;
import naga.x.event.EventListener;
import naga.x.game.template.TemplateService;
import naga.x.game.time.DayListener;
import naga.x.game.time.TimeUpdater;
import naga.x.net.Session;
import naga.x.net.annotation.OPHandler;
import naga.x.net.impl.pomelo.annotation.PomeloOP;
import naga.x.service.ServiceException;
import naga.x.util.TimeUtils;

/**
 * 物品兑换活动（集字活动）
 * @author yang.li
 *
 */
@OPHandler
public class ExchangeActivityService extends ActivityService implements EventListener, DayListener {

	protected List<ItemExchangeTemplate> templates;
	
	public long beginTime = TimeUtils.parse("1900-05-25 00:00:00").getTime();
	public long endTime = TimeUtils.parse("1900-06-25 23:59:59").getTime();
//	ActivityIds.ACTIVITY_COLLECT_WORDS
	
	@Override
	public void startup() throws ServiceException {
		templates = App.getApp().getServiceManager().get(TemplateService.class).getTemplatesList(ItemExchangeTemplate.class);
		App.getApp().getEventManager().register(this);
		TimeUpdater.getInstance().addDayListener(this);
	}

	@Override
	public void shutdown() throws ServiceException {
	}
	
	@Override
	public boolean dayChanged() {
		if (!isValid()) {
			Server.broadcast(new ActivityStatePush(ActivityIds.ACTIVITY_COLLECT_WORDS, STATE_CLOSED));
			return false;
		}
		return true;
	}

	@Override
	public int[] getEventTypes() {
		return new int[] { GameEvents.EVENT_PLAYER_LOADED };
	}

	@Override
	public void handleEvent(Event event) {
		playerLoaded(event.getParameter(0));
	}
	
	private void playerLoaded(Player player) {
		if (isValid()) {
			player.send(new ActivityStatePush(ActivityIds.ACTIVITY_COLLECT_WORDS, STATE_OPENED));
		}
	}

	@PomeloOP(PomeloRoute.ACTIVITY_ITEM_EXCHANGE_INFO)
	protected void requestActivityInfo(Session session, ActivityItemExchangeInfoRequest req) {
		if (!isValid()) {
			session.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_NOT_BEGIN));
			return;
		}
		Response packet = new ActivityItemExchangeInfoResponse(req.getSerial(), req.getId(), templates);
		session.send(packet);
	}
	
	@PomeloOP(PomeloRoute.ACTIVITY_ITEM_EXCHANGE_REQUEST)
	protected void requestExchange(Session session, ActivityItemExchangeRequest req) {
		if (!isValid()) {
			session.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_NOT_BEGIN));
			return;
		}
		int index = req.getIndex();
		if (index < 0 || index >= templates.size()) {
			session.send(new HintResponse(req.getSerial(), MessageConst.ILLEGAL_OPERATION));
			return;
		}
		Player player = session.getClient();
		ItemExchangeTemplate template = templates.get(index);
		if (template.getRequireItems().length == 0) {
			session.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_NOT_BEGIN));
			return;
		}
		ItemTemplate itemTemplate = App.getApp().getServiceManager().get(TemplateService.class).get(ItemTemplate.class, template.getItemId());
		if (itemTemplate == null) {
			session.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_NOT_BEGIN));
			return;
		}
		String poolKey = PlayerPool.PROPERTY_LAST_EXCHANGE_DAY + req.getId() + '_' + index;
		if (player.getPool().getIntValue(poolKey) == TimeUpdater.getInstance().today()) {
			session.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_EXCHANGED_TODAY));
			return;
		}
		int needBagGridSize = itemTemplate.isAutoUse() ? 0 : (template.getItemCount() + itemTemplate.getStack() - 1) / itemTemplate.getStack();
		if (player.getBag().getFreeSize() < needBagGridSize) { // 背包空间不足
			session.send(new HintResponse(req.getSerial(), MessageConst.BAG_FULL));
			return;
		}
		ItemInfo lack = player.getBag().removeItems(Cause.ACTIVITY_EXCHANGE, template.getRequireItems());
		if (lack != null) {
			session.send(new HintResponse(req.getSerial(), MessageFormat.format(MessageConst.ITEM_NOT_ENOUGH, lack.getTemplate().getName())));
			return;
		}
		player.getBag().addItemWithoutException(template.getItemId(), template.getItemCount(), Cause.ACTIVITY_EXCHANGE);
		player.poolSet(poolKey, TimeUpdater.getInstance().today());
		session.send(new Response(req.getSerial()));
		session.send(new BatchItemsPush(itemTemplate, template.getItemCount()));
		LOG.info("[ACTIVITY ITEM EXCHANGE]ID[{}]ACT[{}]INDEX[{}]", player.getId(), req.getId(), index);
	}
	
	public boolean isValid() {
		long time = TimeUpdater.getInstance().now();
		return time >= beginTime && time <= endTime;
	}

}
